package com.mecuros.handler.receiver;

import com.alibaba.fastjson.JSON;
import com.mecuros.common.domain.AnchorInfo;
import com.mecuros.common.domain.LogParam;
import com.mecuros.common.domain.TaskInfo;
import com.mecuros.common.enums.AnchorState;
import com.mecuros.handler.handler.impl.SmsHandler;
import com.mecuros.handler.pending.Task;
import com.mecuros.handler.pending.TaskPendingHolder;
import com.mecuros.handler.utils.GroupIdMappingUtils;
import com.mecuros.support.util.LogUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

/**
 * @Classname Receiver
 * @Description 消费MQ的消息
 * @Date 2022/5/15 4:18 下午
 * @Created by yujianbo
 */
@Slf4j
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class Receiver {
    private static final String LOG_BIZ_TYPE = "Receiver#consumer";
    @Autowired
    private ApplicationContext context;

    @Autowired
    private TaskPendingHolder taskPendingHolder;

    @Autowired
    private LogUtils logUtils;

    @KafkaListener(topics = "#{'${austin.business.topic.name}'}", groupId = "austin")
    public void consumer(ConsumerRecord<?, String> consumerRecord, @Header(KafkaHeaders.GROUP_ID) String topicGroupId) {
        Optional<String> kafkaMessage = Optional.ofNullable(consumerRecord.value());
        if (kafkaMessage.isPresent()) {
            List<TaskInfo> TaskInfoLists = JSON.parseArray(kafkaMessage.get(), TaskInfo.class);
            String messageGroupId  = GroupIdMappingUtils.getGroupIdByTaskInfo(TaskInfoLists.get(0));

            /**
             * 每个消息者组 只消费他们自身关系的消息
             */
            if(topicGroupId.equals(messageGroupId)){
                for (TaskInfo taskInfo : TaskInfoLists) {
                    logUtils.print(LogParam.builder().bizType(LOG_BIZ_TYPE).object(taskInfo).build(), AnchorInfo.builder().ids(taskInfo.getReceiver()).businessId(taskInfo.getBusinessId()).state(AnchorState.RECEIVE.getCode()).build());
                    Task task = context.getBean(Task.class).setTaskInfo(taskInfo);
                    taskPendingHolder.route(topicGroupId).execute(task);
                }
            }
        }

    }
}
